//  将传入的数据 进行 改造 增加属性方法

// 单件商品
class UIGoods {
  constructor(goods) {
    this.data = goods
    this.choose = 0
  }
  // 获取总价
  getTotalPrice () {
    return this.data.price * this.choose
  }
  // 是否被选择
  isChoose () {
    return this.choose > 0
  }
  // 选中的数量+1
  increase () {
    this.choose++
  }
  // 选中的数量-1
  decrease () {
    // 数量=0 返回不能减少
    if (this.choose == 0) {
      return
    }
    this.choose--
  }
}

// 整个界面的数据  购物车
class UIData {
  constructor() {
    // 声明一个数组 存放实例化对象
    let uiGoods = []
    //  循环 将 每个实例化对象 发进去数组中
    for (let i = 0; i < goods.length; i++) {
      const uig = new UIGoods(goods[i])
      uiGoods.push(uig)
    }
    this.uiGoods = uiGoods
    // 起送费
    this.deLiveryThreshold = 30
    // 配送费
    this.deLiveryPrice = 5
  }
  // 总价
  getTotalPrice () {
    return this.uiGoods.reduce((total, item) => {
      return total += item.getTotalPrice()
    }, 0)
  }
  // 增加某件 index 商品的选中数量
  increase (index) {
    this.uiGoods[index].increase()
  }
  // 减少某件 index 商品的选中数量
  decrease (index) {
    this.uiGoods[index].decrease()
  }
  // 有没有选中
  isChoose (index) {
    return this.uiGoods[index].isChoose()
  }
  // 得到 全部商品的选中数量 
  getTotalChooseNumber () {
    return this.uiGoods.reduce((total, item) => {
      return total += item.choose
    }, 0)
  }
  // 购物车中有没有商品  用过判断选中数量是否>0
  hasGoodsInCar () {
    return this.getTotalChooseNumber() > 0
  }
  //  总价是否跨过 起送价格
  isCrossDeliveryThreshold () {
    return this.getTotalPrice() >= this.deLiveryThreshold

  }
}

//  界面
class UI {
  constructor() {
    this.UIData = new UIData()
    this.doms = {
      goodsContainer: document.querySelector(".goods-list"),
      // 配送费
      deLiveryPrice: document.querySelector(".footer-car-tip"),
      // 结算
      footerPay: document.querySelector(".footer-pay"),
      footerPayInnerSpan: document.querySelector(".footer-pay span"),
      totalPrice: document.querySelector(".footer-car-total"),
      car: document.querySelector(".footer-car"),
      carBadge: document.querySelector(".footer-car-badge")
    }
    let carRect = this.doms.car.getBoundingClientRect()
    let jumpTarget = {
      x: carRect.left + carRect.width / 2,
      y: carRect.top + carRect.height / 5
    }
    this.jumpTarget = jumpTarget
    this.createHTML()
    this.upDataCar()
    this.Listener()
  };
  //  根据 商品数据建立页面  渲染
  createHTML () {
    this.UIData.uiGoods.forEach((item, index) => {
      this.doms.goodsContainer.innerHTML += `
      <div class="goods-item">
          <img src="./assets/g1.png" alt="" class="goods-pic" />
          <div class="goods-info">
            <h2 class="goods-title">${item.data.title}</h2>
            <p class="goods-desc">${item.data.desc}
            </p>
            <p class="goods-sell">
              <span>月售 ${item.data.sellNumber}</span>
              <span>好评率${item.data.favorRate}</span>
            </p>
            <div class="goods-confirm">
              <p class="goods-price">
                <span class="goods-price-unit">￥</span>
                <span>${item.data.price}</span >
              </p >
      <div class="goods-btns">
        <i data-id ="${index}" class="iconfont i-jianhao"></i>
        <span>${item.choose}</span>
        <i data-id ="${index}" class="iconfont i-jiajianzujianjiahao"></i>
      </div>
            </div >
          </div >
      `
    })
  }

  // 监听事件 
  Listener () {
    this.doms.car.addEventListener("animationend", function () {
      this.classList.remove("animate")
    })
  }
  // 增加商品数量
  increase (index) {
    this.UIData.increase(index)
    this.upDataGoodsItem(index)
    this.upDataCar()
    this.jump(index)
  }
  // 减少商品数量
  decrease (index) {
    this.UIData.decrease(index)
    this.upDataGoodsItem(index)
    this.upDataCar()
  }

  // 更新 某个商品的显示状态
  upDataGoodsItem (index) {
    let goodsDom = this.doms.goodsContainer.children[index]
    // console.log(goodsDom)
    if (this.UIData.isChoose(index)) {
      goodsDom.classList.add("active")
    } else {
      goodsDom.classList.remove("active")
    }
    let span = goodsDom.querySelector(".goods-btns span")
    span.textContent = this.UIData.uiGoods[index].choose
  }
  // 更新购物车 
  upDataCar () {
    // 总价
    let total = this.UIData.getTotalPrice()
    // 更新总价
    this.doms.carBadge.textContent = this.UIData.getTotalChooseNumber()
    this.doms.totalPrice.textContent = total.toFixed(2)
    if (this.UIData.hasGoodsInCar()) {
      this.doms.car.classList.add("active")
    } else {
      this.doms.car.classList.remove("active")
    }
    this.carAnimate()
    this.doms.deLiveryPrice.textContent = `配送费¥${this.UIData.deLiveryPrice}`
    if (this.UIData.isCrossDeliveryThreshold()) {
      // 到达起送费
      this.doms.footerPay.classList.add("active")
    } else {
      this.doms.footerPay.classList.remove("active")
      // 还差多少钱
      let dis = Math.round(this.UIData.deLiveryThreshold - total)
      this.doms.footerPayInnerSpan.textContent = `还差¥${dis}元起送`
    }
  }
  // 添加购物车动画
  carAnimate () {
    this.doms.car.classList.add("animate")
    this.doms.car.addEventListener("animationend", function () {
      this.classList.remove("animate")
    })
  }
  //  +号跳跃动画
  jump (index) {
    let btnAdd = this.doms.goodsContainer.children[index].querySelector(".i-jiajianzujianjiahao")
    console.log(btnAdd)
    let rect = btnAdd.getBoundingClientRect()
    let start = {
      x: rect.left,
      y: rect.top
    }
    // 
    let div = document.createElement("div")
    div.className = "add-to-car"
    let i = document.createElement("i")
    i.className = "iconfont i - jiajianzujianjiahao"
    // 初始位置
    div.style.transform = `translateX(${start.x}px)`
    i.style.transform = `translateY(${start.y}px)`
    div.appendChild(i)
    document.body.appendChild(div)
    // 强行渲染
    div.clientWidth
    // 结束位置
    div.style.transform = `translateX(${this.jumpTarget.x}px)`,
      i.style.transform = `translateY(${this.jumpTarget.y}px)`
    // 过渡结束
    let that = this
    div.addEventListener("transitionend", function () {
      div.remove()
      that.carAnimate()
    }, {
      once: true //触发一次
    })
  }

}

let ui = new UI()
ui.doms.goodsContainer.addEventListener("click", function (e) {
  console.log(e.target.dataset.id)
  if (e.target.classList.contains("i-jiajianzujianjiahao")) {
    ui.increase(+e.target.dataset.id)
  } else if (e.target.classList.contains("i-jianhao")) {
    ui.decrease(+e.target.dataset.id)
  }
})